<?php
//function business_listing_user_admin(){ 
    global $user_ID, $wpdb, $current_user;
    
    get_currentuserinfo();
    
    //is_user_logged_in()
    if($current_user->ID <= 0 || $user_ID <=0 ){              
        wp_redirect_to('/wp-admin/');
        exit;
    } /*if($current_user->ID > 0 && $current_user->user_status < 2 && $current_user->user_level != 10 ){
        error_('Your account is waiting for approval');
        return;
    }*/
    
    $post_id = $_GET['bs_id'];
    
    if($_POST['btnSubmit']) {
        $file_path_new = '';
        if(1){ 
            $root_folder = $_SERVER['DOCUMENT_ROOT'];
            $allowedExts = array("jpg", "jpeg", "gif", "png");
            $extension = end(explode(".", $_FILES["field_photo"]["name"]));
            //$_FILES["field_photo"]["size"] < 1024*1024*2) && 
            if ((($_FILES["field_photo"]["type"] == "image/gif")
                || ($_FILES["field_photo"]["type"] == "image/jpeg")
                || ($_FILES["field_photo"]["type"] == "image/png")
                || ($_FILES["field_photo"]["type"] == "image/pjpeg"))
                && (in_array($extension, $allowedExts))) {
                if ($_FILES["field_photo"]["error"] > 0) {
                    echo "Return Code: " . $_FILES["field_photo"]["error"] . "<br>";
                } else {
                    if (file_exists($root_folder."/wp-content/uploads/business-listing/". $_FILES["field_photo"]["name"])){
                        echo $_FILES["field_photo"]["name"] . " already exists. ";
                    } else {
                          move_uploaded_file($_FILES["field_photo"]["tmp_name"],
                          $root_folder."/wp-content/uploads/business-listing/" . $_FILES["field_photo"]["name"]);
                          $file_path_new = "wp-content/uploads/business-listing/".$_FILES["field_photo"]["name"];
                          
                   }//uppload
                }
            } // check file            
        }      
        //fields
        $fields = array();
        
        $sql = "SELECT * FROM ".$wpdb->prefix."category_fields wpcf 
                            INNER JOIN ".$wpdb->prefix."content_fields wpcf1 ON wpcf.field_id=wpcf1.id
                            WHERE wpcf.category_id=".$_POST['category']. " ORDER BY wpcf1.weight";
        $db = $wpdb->get_results($sql);
        foreach($db as $field) {
           
            if($field->field_key=='field_photo') {                
                if($post_id > 0) $file_path = get_post_meta($post_id, $field->field_key,TRUE);
                if($_POST['file_photo_remove']==1) {
                    $fields[$field->field_key] = NULL;
                    $file_path = $_SERVER['DOCUMENT_ROOT'].'/'.$file_path;
                    @unlink($file_path);
                } else {
                    if($file_path_new!='' && $file_path_new!=$file_path)
                        $fields[$field->field_key] = $file_path_new;
                    else
                        $fields[$field->field_key] = $file_path;
                }
            } else
                $fields[$field->field_key] = $_POST[$field->field_key];
        }      
        
        $slug = sanitize_title($fields['field_name']);
        // Create busines listing object
        $bs_post = array(
          'post_title'    => $fields['field_name'],
          'post_content'  => $fields['field_description'],
          'post_status'   => $_POST['field_approve'], //waiting for approvel by admin
          'post_author'   => $_POST['company'],
          'post_type'   => 'businesslisting',          
          'post_date'      => date('Y-m-d H:i:s'), //The time post was made.
          'post_date_gmt'  => date('Y-m-d H:i:s'), //The time post was made, in GMT.
          'post_modified'      => date('Y-m-d H:i:s'), //The time post was made.
          'post_modified_gmt'  => date('Y-m-d H:i:s'), //The time post was made, in GMT.
          'post_excerpt'   => null, //For all your post excerpt needs.
          'post_name'      => $slug, // The name (slug) for your post
          'post_parent'    => 0, //Sets the parent of the new post.
          'comment_status' => 'closed'          
        );
        if($post_id <= 0 ) {
            // Insert the business listing into the database
            $post_id = wp_insert_post( $bs_post, $wp_error );
            update_post_meta($post_id, 'business_count', 0);
            update_post_meta($post_id, 'search_count', 0);
            update_post_meta($post_id, 'detail_count', 0);
            error_('Your data has been created successfully!','confirm');
        } else {
            // update the business listing into the database            
            $bs_post = array(
              'ID' => $post_id,
              'post_title'    => $fields['field_name'],
              'post_content'  => $fields['field_description'],
              'post_author'   => $_POST['company'],
              'post_status'   => $_POST['field_approve'], //waiting for approvel by admin
              'post_modified'      => date('Y-m-d H:i:s'), //The time post was made.
              'post_modified_gmt'  => date('Y-m-d H:i:s'), //The time post was made, in GMT.
              'post_excerpt'   => null, //For all your post excerpt needs.
              'post_name'      => $slug // The name (slug) for your post             
            );
            wp_update_post($bs_post);
            if($_POST['field_approve']=='publish') {
                $post_tmp = get_post($post_id);   
                business_listing($post_tmp->post_author);
            } 
            error_('Your data has been updated successfully!','confirm');
        }
        //update term for post
        $sql = 'SELECT count(*) as total FROM '.$wpdb->prefix.'term_relationships tr
                    INNER JOIN '.$wpdb->prefix.'term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id                   
                    WHERE tr.object_id='.$post_id.' AND tt.term_id='.$_POST['category'];
        $db_row = $wpdb->get_row($sql);
        if($db_row->total <=0 ){    
            $sql = "SELECT * FROM ".$wpdb->prefix."terms t
                    INNER JOIN ".$wpdb->prefix."term_taxonomy tt ON tt.term_id = t.term_id
                    WHERE t.term_id=".$_POST['category']; 
            $db_term = $wpdb->get_row($sql);
            if(count($db_term)>0) {
                $sql = "INSERT INTO ".$wpdb->prefix.'term_relationships (object_id,term_taxonomy_id) 
                            VALUES ('.$post_id .','.$db_term->term_taxonomy_id.")";
                $wpdb->query($sql);
            }
        }
        
        //update post meta
        foreach($fields as $field => $value){
            if($field != 'field_name' && $field != 'field_description') {                
                //update post meta               
                update_post_meta($post_id, $field, $value);
            }
        }
        
    }
    if($_POST['btnDelete']) {
        $_IDs = $_POST['chk_item'];       
        foreach($_IDs as $id => $post_id){
            $post = array(
                        'ID' => $post_id,
                        'post_status' => 'trash'
                    );
            wp_update_post($post);
        }
    }
    if($_POST['btnApprove']) {
        $_IDs = $_POST['chk_item'];       
       
        foreach($_IDs as $id => $post_id){
            $post = array(
                        'ID' => $post_id,
                        'post_status' => 'publish'
                    );
            wp_update_post($post);
            $post_tmp = get_post($post_id);   
            business_listing($post_tmp->post_author);
        }
    }
    ?>
    
    <div id="business_lists">
        <!-- <div id="tabs">
            <ul>
                <li <?php print ($_GET['tab'] ==''?'class="selected"':'');?>>
                    <a href="/businesspartners/business-listing/">Business Listing</a>
                </li>
                <li <?php print ($_GET['tab'] =='update'?'class="selected"':'');?>>Addnew/Update</li>
            </ul>
        </div>-->
        <?php if($_GET['tab']=='') { 
            
                $status = ($_POST['status'])? $_POST['status'] : $_GET['status'];
                // if ( $status=='' ) $status = 'pending';
                if ( $status=='' ) $status = 'all';
                
            ?>
        <div id="table-company" >
            <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" id="frmBusinessListing"  name="frmBusinessListing" enctype="multipart/form-data">
                <div class="tab-header" style="width: 740px;">
                    Select: <select id="status" name="status">
                                <option value="all">-All-</option>
                                <option value="pending" <?php print ($status=='pending'?'selected="selected"':'');?>>Pending&nbsp;</option>
                                <option value="publish" <?php print ($status=='publish'?'selected="selected"':'');?>>Approved&nbsp;</option>
                                <option value="trash" <?php print ($status=='trash'?'selected="selected"':'');?>>Deleted&nbsp;</option>
                           </select>
                           &nbsp; &nbsp; 
                           Filter by Category: &nbsp;
                           <?php
                            $terms = get_terms( 'bs_category', 'orderby=name&hide_empty=0&parent=0' ); 
                            $select_category = '<select id="fcategory" name="fcategory">';
                            $select_category .= '<option value="">--Select category --</option>';
                            foreach($terms as $term) {                  
                                $select_category .= '<option value="'.$term->term_id.'" '.( ($_GET['fcat']==$term->term_id)?"selected=selected":'').'>&nbsp;'.$term->name.'&nbsp;</option>';
                            }
                            $select_category .= '</select>'; 
                             
                            print $select_category;                            
                           ?>
                           &nbsp;&nbsp;
                           <input type="text" size="30" id="txtSearchBS" name="txtSearchBS" value="<?php print $_GET['q'];?>"  />&nbsp;
                           <input class="button" type="button" value="Search" id="btnSearch" name="btnSearch" />                      
                </div>            
                <div class="header row" style="width: 846px;">      
                    <div class="col2 col">#</div>
                    <div class="col2 col"><input type="checkbox" id="chk_all" name="chk_all" /></div>
                    <div class="col4 col" style="width: 300px;">Business Name</div>  
                    <div class="col4 col" style="width: 200px;">Owner</div>              
                    <div class="col7 col">Status</div>
                    <div class="col7 col">Details</div>
                </div>
                <?php
                   $post_where = ''; $status = $_GET['status'];
                   
                    if( !empty($_GET['status']))  {           
                        if($_GET['status']!='all') $post_where = " AND  p.post_status = '".$_GET['status']."'";
                    } else {					
						$status = 'all';
                        //$post_where = "AND 1=1 ";
                    } 
                    if(!empty($_GET['fcat']))  {                        
                        $post_where .= " AND  t.term_id =".$_GET['fcat'];
                    }                   
                    if(!empty($_GET['q']))  {                        
                        $post_where .= " AND  p.post_title like '%".$_GET['q']."%'";
                    }
                   
                   $page_size = 20;
                   $current_page = ($_GET['pg'] >0)? $_GET['pg'] : 1;
                   $page = ($current_page - 1)*$page_size;
                   if($page < 0 ) $page = 1; 
                   //get total rows
                   
                   $sql = "SELECT p.ID, post_title, post_status, t.term_id, com.name  FROM ".$wpdb->prefix."posts  p
                            INNER JOIN ".$wpdb->prefix."term_relationships tr ON tr.object_id = p.ID                            
                            LEFT JOIN ".$wpdb->prefix."term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                            INNER JOIN ".$wpdb->prefix."terms t ON t.term_id = tt.term_id 
                            INNER JOIN ".$wpdb->prefix."company com ON com.user_id = p.post_author
                            WHERE p.post_type='businesslisting' AND p.post_status in ('pending','publish','trash') 
                                $post_where";
                            
                   $sql1 = "SELECT count(*) as total  FROM (".$sql.") as tblCount";
                   $bs_posts = $wpdb->get_results($sql1);
                   $i = 1;
                   $total_rec = $bs_posts[0]->total;
                   $total_page = (int)($bs_posts[0]->total/$page_size);
                   if($total_page < 1 ) 
                        $total_page = 1;
                   else
                   if($total_page*$page_size < $bs_posts[0]->total ) $total_page++;
                  
                   $from_row = $page_size*($current_page-1) + 1;
                   $to_row  = $page_size*($current_page-1) + $page_size;
                   if($to_row > $total_rec) $to_row  = $total_rec;
                    
                   $sql =  $sql." ORDER BY p.post_date DESC LIMIT $page, $page_size";                            
                   $bs_posts = $wpdb->get_results($sql);
                   
                   foreach($bs_posts as $post){
                ?>
                <div class="row" style="width: 846px;">     
                    <div class="col2 col"><?php print $i++;?></div>           
                    <div class="col2 col"><input class="chk_item" type="checkbox" id="chk_item<?php print $post->ID; ?>" name="chk_item[]" value="<?php print $post->ID; ?>" /></div>
                    <div class="col4 col" style="width: 300px;"><?php print $post->post_title;?></div>
                    <div class="col4 col" style="width: 200px;"><?php print $post->name;?></div>  
                    <div class="col7 col">
                        <?php 
                              if($post->post_status=='pending') print '<font color=#bd000>Waiting for Approval</font>';
                              else  if($post->post_status=='trash') print 'Deleted';
                                else print 'Approved';
                        ?>
                    </div>
                    <div class="col7 col">
                        <?php //if($post->post_status != 'trash') { ?>
                        <a href="?page=accm&tabmenu=business&tab=update&bs_id=<?php print  $post->ID;?>&cat_id=<?php print  $post->term_id;?>">View</a>
                        <?php //} else print 'Deleted';?>
                    </div>                
                </div>
                <?php } 
                    if($i == 1 )
                        print '<div style="float: left; width: 620px; text-align: center;" class="row col">No Business Listing Found</div>';
                ?> 
                <div class="footer" style="width: 846px;">
                    <div class="paging">
                        <div class="left">Displaying <strong><?php print $from_row; ?></strong> - <strong><?php print $to_row ; ?></strong> of <strong><?php print $total_rec;?> </strong></div>
                        <div class="right" style="width: 620px;">Go to: 
                         <?php for($p = 1; $p <= $total_page; $p++ ) { 
                            if($p==$current_page) { ?>
                            <a class="curent-page" href="#"><?php print $p;?></a>&nbsp;
                            <?php } else { ?> <a href="?page=accm&tabmenu=business&pg=<?php print $p;?>&status=<?php print $status;?>&fcat=<?php print $_GET['fcat'];?>&q=<?php print $_GET['q'];?>"><?php print $p;?></a><?php } ?>
                         <?php } ?>
                        </div>
                    </div> 
                    <div style="float:  left; padding: 10px;">
                        <input type="button" value="Add New" id="btnBLAddnewAdmin" name="btnBLAddnewAdmin" class="button">
                        <input class="button" type="submit" id="btnApprove" name="btnApprove" value="Approve" />
                        <input class="button" type="submit" id="btnDelete" name="btnDelete" value="Delete" />
                    </div>
                </div>
                <div style="float:  left; padding: 10px; line-height: 20px;">  
                    <strong>Note:</strong><br />
                    *If "<strong>Company IsActive?</strong>" is <strong>NO</strong>, the business items are considered disabled and not viewable in Business Listing Page.<br />                
                    *If "<strong>IsDeleted?</strong>" is <strong>YES</strong>, the business items are considered disabled and not viewable in Business Listing Page.<br />                
                    *If you have deleted an item accidentally, you can restore it through database. Please contact your immediate web administrator to restore important data.<br />                
                    *Kindly manage your items properly. 
                </div>
            </form>
        </div>
        <?php } 
            //show form to update/addnew
            if($_GET['tab']=='update') {
                if( $post_id > 0) {
                    $post = get_post($post_id);   
                    $cat_id = $_GET['cat_id'];
                } else {
                    $cat_id = $_POST['category'];
                }        
                
                //get company
                $sql = "SELECT user_id, name FROM ".$wpdb->prefix."company WHERE approved = 1 ORDER BY name";
                $db_com = $wpdb->get_results($sql);
                $select_company = '<select id="company" name="company">';
                $select_company .= '<option value="">--Select company --</option>';
                foreach($db_com as $company){
                    $select_company .= '<option value="'.$company->user_id.'" '.($company->user_id==$post->post_author?'selected=selected':'').' >'.$company->name.'</option>';
                }
                $select_company .= '</select>'; 
                
                $terms = get_terms( 'bs_category', 'orderby=name&hide_empty=0&parent=0' ); 
                $select_category = '<select id="category" name="category">';
                $select_category .= '<option value="">--Select category --</option>';
                foreach($terms as $term) {                  
                    $select_category .= '<option value="'.$term->term_id.'" '.(($cat_id==$term->term_id)?"selected=selected":'').'>&nbsp;'.$term->name.'&nbsp;</option>';
                }
                $select_category .= '</select>';  ?>
    <div id="business_lists_update" class="admin-post">
        <form enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" id="frmBusinessListing"  name="frmBusinessListing">
            <?php if($_GET['bs_id']>0) { ?>
            <div class="form-item">
                <div class="left">Page Impression:</div>
             	<div class="right" style="padding-top: 5px;">
                    By Business Listing: <?php print get_post_meta($post_id,'business_count',TRUE);?><br />
                    By Search Listing: <?php print get_post_meta($post_id,'search_count',TRUE);?><br />
                    By Business Detail: <?php print get_post_meta($post_id,'detail_count',TRUE);?><br />
                </div>
            </div>
            <?php }              
            ?>
             <?php if($post_id < 0 ) { ?>
            <div class="form-item">
                <div class="left">Company: </div>
                <div class="right"><?php  print $select_company ?>
                </div>
            </div> 
             <?php } else { ?>
             <input  type="hidden"  id="company" name="company" value="<?php print $company->user_id; ?>"/>
            <?php    
             }
             
             if($cat_id<=0) { 
            ?>   
            <div class="form-item">
                <div class="left">Category: </div>
                <div class="right"><?php  print $select_category; ?>
                    <?php if($post_id <=0 && $_POST['category'] <=0 ) { ?>
                    <input type="submit" value="Go" id="btnCreate" name="btnCreate" class="button" />
                    <?php } ?>
                </div>
            </div>    
            <?php
            }
                if($_POST['category'] > 0 || $post_id > 0 ) { 
                    
                    $sql = "SELECT * FROM ".$wpdb->prefix."category_fields wpcf 
                            INNER JOIN ".$wpdb->prefix."content_fields wpcf1 ON wpcf.field_id=wpcf1.id
                            WHERE wpcf.category_id=".$cat_id . " ORDER BY wpcf1.weight";
                    $db = $wpdb->get_results($sql);
                    //ad
                    foreach($db as $field) {                         
                        
                        $class_requied = ($field->required)?" required":'';;
                        $required = ($field->required)?'<font color="#bd0000">*</font>':'';
                        $val = '';
                        if( $post_id > 0 )                       
                            $val = get_post_meta($post_id,$field->field_key,TRUE);
                        else
                            $val = $_POST[$field->field_key];
                            
                        $input = ''; $class_left = '';
                        switch($field->field_type) {
                            case 'textfield':                                
                                $class_left = ($field->field_key=='field_mumomeetingrooms')?'textarea-normal':'';  
                                if('field_email' == $field->field_key) $class_requied .= 'email';
                                if($field->field_key == 'field_name') $val = $post->post_title;
                                
                                $input = '<input value ="'.$val.'" type="text" id="'.$field->field_key.'" name="'.$field->field_key.'" class="input '.$class_requied.'">';
                            break;
                            case 'datetime':                               
                                $input = '<input value ="'.$val.'" type="text" id="'.$field->field_key.'" name="'.$field->field_key.'" class="input '.$class_requied.' datetime">';
                            break;
                            case 'upload':
                                $input = '<input type="file" id="'.$field->field_key.'" name="'.$field->field_key.'" class="input">';
                                
                                if($val){
                                    $input .= '<div style="float: left; width: 100%; margin-top: 10px; ">
                                                    <div style="float: left; width: 60%;">
                                                        [Large Size]<br />
                                                        <img src="'. site_url($val).'" width=200 height=200 style="margin-top: 5px;">
                                                    </div>
                                                    <div style="float: left; width: 40%;">[Thumbnail size]<br />
                                                        <img src="'.site_url($val).'" width=100 height=100 style="margin-top: 5px;"></div>
                                                    <div style="float: left; width: 100%; border-top: solid 1px #ccc; padding-top: 5px; margin-top: 5px;">
                                                        <input type="checkbox" name="file_photo_remove" id="file_photo_remove" value=1>&nbsp;Remove photo<br />
                                                        <em>Kindly check if you wish to remove the current photo.</em>
                                                    </div>
                                               </div>';
                                }
                            break;
                            case 'textarea':   
                                $val = ($field->field_key!='field_description')?get_post_meta($post_id,$field->field_key,TRUE) : $post->post_content; 
                                $class_left = ($field->field_key!='field_description')?'textarea-normal':'';                             
                                $input = '<textarea id="'.$field->field_key.'" name="'.$field->field_key.'" rows=5>'.$val.'</textarea>';
                            break;
                            
                            case 'msubcategory':
                                //$pid = ($_POST['category']>0 && $field->field_type=='subcategory')? $_POST['category']:0;
                                if(($_POST['category']>0 || $_GET['cat_id']>0) && ($field->field_type=='subcategory' 
                                    || $field->field_type=='msubcategory')){
                                     $pid = ($_POST['category']>0)?$_POST['category']:$_GET['cat_id'];
                                     $pid = ($pid <0)?0:$pid;
                                }
                                $input = select_control($field->field_key,$field->field_type,$pid, $val, true, $class_requied);
                            break;
                            
                            case 'selectlist':
                            break;
                            
                            case 'radio':
                                $checked_true = '';
                                $checked_false = '';
                                if( $post_id > 0 ) {                   
                                    $val = get_post_meta($post_id,$field->field_key,TRUE);
                                    if($val == 1)  
                                        $checked_true = 'checked=true';
                                    else
                                        $checked_false = 'checked=true';
                                }
                                $input = '<div style="margin-top: 5px;">
                                            <input '.$checked_true.' type="radio" name="'.$field->field_key.'" value=1 > Partners ';
                                $input .= '<input '.$checked_false.' type="radio" name="'.$field->field_key.'" value=0 > Free</div>';
                            break;
                            
                            case 'checkbox':
                                $val = get_post_meta($post_id,$field->field_key,TRUE);
                                if($val == 1) $checked = 'checked=true';
                                $input = '<input '.$checked.' type="checkbox" name="'.$field->field_key.'" value=1 >'.$field->field_label.'</div>';
                            break;
                            
                            default:                                
                                if($field->field_type=='subcategory') {
                                    $pid = ($_POST['category']>0)? $_POST['category']:($_GET['cat_id']>0?absint($_GET['cat_id']):0);
                                }
                                $val = get_post_meta($post_id,$field->field_key,TRUE);
                                $input = select_control($field->field_key,$field->field_type,$pid, $val, false, $class_requied);
                            break;
                            
                        }
                        //print field control
                        $note = '';
                        if($field->note) $note = '<div class="note">'.html_entity_decode($field->note).'</div>';
                        print '<div class="form-item">
                                    <div class="left '.$class_left.'">'.$field->field_label.$required.': </div>
                                    <div class="right">'.$input.$note.'</div>
                               </div>';
                    } //for
                    
                    print ' <div class="form-item">
                                    <div class="left">Approve:</div>
                                    <div class="right" style="padding-top: 5px;">
                                        <input type="radio" name="field_approve" value="publish" '.($post->post_status=='publish'?'checked=true':'').' > Yes 
                                        <input type="radio" name="field_approve" value="pending" '.($post->post_status=='pending'?'checked=true':'').'> No 
                                    </div>
                            </div>                           
                            <div class="form-item">
                                    <div class="left"></div>
                                    <div class="right">
                                        <input type="hidden" value="'.$cat_id.'" id="category" name="category">                                    
                                        <input type="hidden" value="'.$bs_ID.'" id="field_bs_id" name="field_bs_id">
                                        <input type="reset" id="btnReset" name="btnReset" class="button" value="Reset">
                                        <input type="submit" id="btnSubmit" name="btnSubmit" class="button" value="Submit">
                                    </div>
                                </div>';
                }                
            ?>
        </form>
    </div>
           <?php 
            }
        ?>
    </div>
<?php
//}
?>
<script>
    (function($){
        $(document).ready(function() {
            $('#status').change(function(){
                fcat = $('#fcategory').val();
                q = $('#txtSearchBS').val();                
                window.location = '?page=accm&tabmenu=business&status=' + $(this).val()+'&fcat='+fcat+'&q='+q;
            });
            $('#fcategory').change(function(){
                status = $('#status').val();
                q = $('#txtSearchBS').val();  
                              
                window.location = '?page=accm&tabmenu=business&fcat=' + $(this).val()+'&status='+status+'&q='+q;
            });
            $('#btnSearch').click(function(){
                status = $('#status').val();
                cat = $('#fcategory').val();
                q = $('#txtSearchBS').val();  
                              
                window.location = '?page=accm&tabmenu=business&fcat=' + $(this).val()+'&status='+status+'&q='+q;
            });
        });
    })(jQuery);
</script>